package com.sunday.scoremanager.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.adapter.CommonAdapter;
import com.sunday.common.widgets.adapter.ViewHolder;
import com.sunday.common.widgets.pickerview.TimePickerView;
import com.sunday.common.widgets.recyclerView.HorizontalDividerItemDecoration;
import com.sunday.scoremanager.R;
import com.sunday.scoremanager.base.BaseApp;
import com.sunday.scoremanager.base.BaseLazyFragment;
import com.sunday.scoremanager.entity.Income;
import com.sunday.scoremanager.entity.RecordDetail;
import com.sunday.scoremanager.http.ApiClient;

import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/10/26.
 */

public class IncomeFragment extends BaseLazyFragment {


    @Bind(R.id.total_profit)
    TextView totalProfit;
    @Bind(R.id.available_profit)
    TextView availableProfit;
    @Bind(R.id.score)
    TextView score;
    @Bind(R.id.rl_score_profit)
    RelativeLayout rlScoreProfit;
    @Bind(R.id.hy_score)
    TextView hyScore;
    @Bind(R.id.rl_hy_profit)
    RelativeLayout rlHyProfit;
    @Bind(R.id.score_time)
    TextView scoreTime;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.btn_withdraw)
    TextView btnWithdraw;

    private long memberId;
    private List<RecordDetail> dataSet = new ArrayList<>();
    private LinearLayoutManager layoutManager;
    private CommonAdapter<RecordDetail> adapter;

    public static IncomeFragment newInstance() {
        IncomeFragment fragment = new IncomeFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isPrepared = true;
        lazyLoad();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_income, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        if (!isPrepared || !isVisible) {
            return;
        }
        isPrepared = false;
        memberId = BaseApp.getInstance().getMember().getSellerId();
//        ptrFrame.autoRefresh();
        initView();
        getData();
    }

    private void initView() {
        //
        btnWithdraw.setVisibility(BaseApp.getInstance().getMember().getPermission() == 1 ? View.VISIBLE : View.GONE);

        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new CommonAdapter<RecordDetail>(mContext, R.layout.list_income_item, dataSet) {
            @Override
            public void convert(ViewHolder holder, RecordDetail recordDetail) {
                bind(holder, recordDetail);
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(mContext)
                .drawable(R.drawable.shape_divider)
                .build());

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }


    private void bind(ViewHolder holder, RecordDetail recordDetail) {
        TextView score = holder.getView(R.id.profit);
        TextView time = holder.getView(R.id.time);
        TextView from = holder.getView(R.id.from);
        score.setText(recordDetail.getAmount().setScale(2, RoundingMode.HALF_UP) + "");
        time.setText(recordDetail.getTime());
        from.setText(recordDetail.getMemo());

    }

    private Income income;

    public void getData() {
        memberId=BaseApp.getInstance().getMember().getSellerId();
        Call<ResultDO<Income>> call = ApiClient.getApiAdapter().myAssets(memberId, 5, 2);
        call.enqueue(new Callback<ResultDO<Income>>() {
            @Override
            public void onResponse(Call<ResultDO<Income>> call, Response<ResultDO<Income>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    income = response.body().getResult();
                    updateView();
                    getIncomeDetail();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Income>> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void updateView() {
        if (income == null) {
            return;
        }
        totalProfit.setText(income.getTotalIncome().setScale(2, RoundingMode.HALF_UP) + "");
        availableProfit.setText(income.getNowIncome().setScale(2, RoundingMode.HALF_UP) + "");
        score.setText(income.getScore().setScale(2, RoundingMode.HALF_UP) + "");
        hyScore.setText(income.getHuaiYaScore().setScale(2, RoundingMode.HALF_UP) + "");
    }


    private int pageNo = 1;
    private String selectDate;
    private boolean isCanloadMore;
    private int lastVisibleItem;

    private void getIncomeDetail() {
        Call<ResultDO<List<RecordDetail>>> call = ApiClient.getApiAdapter().recordDetail(memberId, 5, 2, pageNo, Constants.PAGE_SIZE, selectDate);
        call.enqueue(new Callback<ResultDO<List<RecordDetail>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<RecordDetail>>> call, Response<ResultDO<List<RecordDetail>>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    if (pageNo == 1) {
                        dataSet.clear();
                    }
                    dataSet.addAll(response.body().getResult());
                    if (response.body().getResult() != null && response.body().getResult().size() == Constants.PAGE_SIZE) {
                        pageNo++;
                        isCanloadMore = true;
                    } else {
                        isCanloadMore = false;
                    }
                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<RecordDetail>>> call, Throwable t) {

            }
        });
    }


    private TimePickerView timePickerView;

    @OnClick({R.id.rl_score_profit, R.id.rl_hy_profit, R.id.btn_withdraw, R.id.score_time})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_score_profit:
                intent = new Intent(mContext, MyScoreActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_hy_profit:
                intent = new Intent(mContext, HyProfitActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_withdraw:
                intent = new Intent(mContext, SelectAccountActivity.class);
                startActivity(intent);
                break;
            case R.id.score_time:
                timePickerView = new TimePickerView(mContext, TimePickerView.Type.YEAR_MONTH);
                timePickerView.setTime(new Date());
                timePickerView.setCyclic(true);
                timePickerView.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM", Locale.CHINESE);
                        selectDate = sdf.format(date);
                        scoreTime.setText(sdf1.format(date));
                        pageNo = 1;
                        getData();
                        timePickerView.dismiss();
                    }
                });
                timePickerView.show();
                break;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint()){
            getData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
